<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>通道配置管理</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="stylesheet" href="{{asset('/layuiadmin/layui/css/layui.css')}}" media="all">
  <link rel="stylesheet" href="{{asset('/layuiadmin/style/admin.css')}}" media="all">
    <link rel="stylesheet" href="{{asset('/layuiadmin/layui/css/formSelects-v4.css')}}" media="all">
  <style>
    .edit{background-color: #ed9c3a;}
    .shenhe{background-color: #429488;}    
    .see{background-color: #7cb717;} 
    .cur{color:#009688;}
    .del {background-color: #e85052;}
    #demo li{
        width:300px;
     }
     .companyActive{
      background: #3475c3;
      border-radius: 4px;
      color: #fff;
     }
     .companylist{
      margin:6px 0;
     }
     .companylist:hover{
      cursor: pointer;
     }
    .layui-table-cell {
      overflow: visible;
    }
    .layui-table-box {
      overflow: visible;
    }

    .layui-table-body {
      /* overflow: visible; */
      overflow: auto;
    }
    /* 设置下拉框的高度与表格单元相同 */
    td .layui-form-select{
      margin-top: -10px;
      margin-left: -15px;
      margin-right: -15px;
    }
    .layui-form-select .layui-input{
      margin-top:5px;
    }
  </style>
</head>
<body>

  <div class="layui-fluid">
    <div class="layui-row layui-col-space10" style="margin-top:0px">
      <div class="layui-row layui-col-space10">
        <div class="layui-col-xs4 layui-col-md4">
            <div class="layui-card">
                <div class="layui-card-header">
                  <div style="display:flex;justify-content: space-between;">
{{--                    <div>通道列表</div>--}}
                      <div class="layui-btn-container" style="font-size:14px;">
                          <a class="layui-btn layui-btn-primary" id="addcompany" style="background-color:#3475c3;border-radius: 5px;border:none;color:#fff;display: block; margin-top:2px">一键导入</a>
                      </div>
                      <div class="layui-btn-container" style="font-size:14px;">
                          <a class="layui-btn layui-btn-primary" id="download-mch-bet"  style="background-color:#3475c3;border-radius: 5px;border:none;color:#fff;display: block; margin-top:2px">下载当月未配置商户</a>
                      </div>
                      <div class="layui-btn-container" style="font-size:14px;">
                          <a target="_blank" href="https://wanfutong.oss-cn-hangzhou.aliyuncs.com/1747707071.xlsx" class="layui-btn layui-btn-primary"  style="background-color:#3475c3;border-radius: 5px;border:none;color:#fff;display: block; margin-top:2px">下载模板</a>
                      </div>
                  </div>
                  
                   
                </div>
                <div class="layui-card-body" style="height:700px;overflow-y: auto;">
                    <div class="li_list" style="display: inline-block; width: 300px; padding: 10px;  overflow: auto;">
                        <ul id="demo"></ul>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6 layui-col-md8">
            <div class="layui-card">
                <div class="layui-card-header">通道详情</div>
                <div class="layui-card-body">
                    <div class="cmdlist-container">
                        <div class="xinxi" style="display: inline-block;">
                          <div class="layui-btn-container" style="font-size:14px;display:flex">
                            <a class="layui-btn layui-btn-primary" id="editcompany" style="background-color:#3475c3;border-radius: 5px;border:none;color:#fff;display: block;width: 60px;">编辑</a>
                            <a class="layui-btn layui-btn-primary" id="getquota" style="background-color:#3475c3;border-radius: 5px;border:none;color:#fff;display: block;width: 100px;margin-left:20px;display:none">获取额度</a>
                          </div>
                            <p class="tongdao_name">通道名称：<span></span></p>
                            <p class="shanghuhao">通道标识：<span></span></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-col-xs8 layui-col-md8">
          <div class="layui-card">
            <div class="layui-card-body">
            <div class="layui-form" lay-filter="component-form-group" style="width:190px;margin-right:10px;display:flex;">
              <div class="layui-form-item" style="display: inline-block;">
                <div class="layui-inline">
                <div class="layui-input-inline">
                <text class="yname">商户号</text>
                <input type="text" name="search_mchid" lay-verify="search_mchid" placeholder="请输入商户号" autocomplete="off" class="layui-input">
                </div>
                </div>
              </div>
              <div class="layui-inline">
                <button class="layui-btn layuiadmin-btn-list" lay-submit="" lay-filter="LAY-app-contlist-search" style="margin-top: 1.3rem;border-radius:5px;margin-bottom: 0;height:36px;line-height: 36px;">
                <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                </button>
              </div>
              <div class="layui-inline" style="display:flex">
                <button class="layui-btn import" style="margin-top: 1.3rem;border-radius:5px;margin-bottom: 0;height:36px;line-height: 36px;margin-left:20px">导入额度</button>
                <button class="layui-btn importlist" style="margin-top: 1.3rem;border-radius:5px;margin-bottom: 0;height:36px;line-height: 36px;margin-left:20px">导入记录</button>
                <button class="layui-btn exportData" style="margin-top: 1.3rem;border-radius:5px;margin-bottom: 0;height:36px;line-height: 36px;margin-left:20px">导出</button>
              </div>
            </div>
              <table class="layui-hide" id="test-table-page" lay-filter="test-table-page"></table>
              <script type="text/html" id="table-content-list">

                <a class="layui-btn layui-btn-normal layui-btn-xs config" lay-event="config">配置</a>
                <a class="layui-btn layui-btn-normal layui-btn-xs storelist" style="margin-left:10px" lay-event="storelist">门店列表</a>
              </script>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div id="add_edit" class="hide" style="display: none;background-color: #fff;">
        <div class="layui-card-body" style="padding: 15px;">
            <div class="layui-form">
                <div class="layui-form-item">
                    <label class="layui-form-label">通道名称:</label>
                    <div class="layui-input-block">
                        <input type="text" placeholder="请输入名称" class="layui-input name">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">月额度启始日:</label>
                    <div class="layui-input-block">
                        <input type="number" placeholder="请输入月额度启始日" class="layui-input quota_date">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">单笔限额:</label>
                    <div class="layui-input-block">
                        <input type="number" placeholder="请输入单笔限额" class="layui-input limit_money">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">显示排序:</label>
                    <div class="layui-input-block">
                        <input type="number" placeholder="请输入排序" class="layui-input sort">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">通道标识</label>
                    <div class="layui-input-block">
                        <input type="text" placeholder="请输入" class="layui-input code">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <div class="layui-footer" style="left: 0;">
                            <button class="layui-btn submit">确定</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <input type="hidden" id="id">
    </div>
    <div id="config_model" class="hide" style="display: none;background-color: #fff;">
        <div class="layui-card-body" style="padding: 15px;">
          
            <div class="layui-form">
                <div class="layui-form-item">
                    <label class="layui-form-label">通道标识:</label>
                    <div class="layui-input-block">
                        <div class="code" style="padding-top: 6px;"></div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">商户号:</label>
                    <div class="layui-input-block">
                        <div class="mch_id" style="padding-top: 6px;"></div>
                    </div>
                </div>
                <div class="layui-row layui-col-space20">
                  <div class="layui-col-md6">
                      <div class="layui-tab">
                      <ul class="layui-tab-title">
                        <li class="layui-this last_title"></li>
                        <li class="now_title"></li>
                        <li class="next_title"></li>
                      </ul>
                      <div class="layui-tab-content">
                        <div class="layui-tab-item layui-show" id="last_month">
                          <div id="zanwu" style="height:250px;padding-top:20px;">暂无配置</div>
                          <div id="hasData">
                            <div class="layui-form-item">
                                <label class="layui-form-label">流水:</label>
                                <div class="layui-input-block">
                                    <div class="liushui" style="padding-top: 6px;"></div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">额度:</label>
                                <div class="layui-input-block">
                                    <input type="number" placeholder="请输入额度" class="layui-input quota">
                                </div>
                            </div>
                            <div class="layui-form-item">
                              <label class="layui-form-label">开始时间:</label>
                              <div class="layui-input-block">
                                <input type="text" style="border-radius:5px" class="layui-input start-item test-item" placeholder="开始时间" lay-key="23">
                              </div>
                            </div>
                            <div class="layui-form-item">
                              <label class="layui-form-label">结束时间:</label>
                              <div class="layui-input-block">
                                <input type="text" style="border-radius:5px" class="layui-input end-item test-item" placeholder="结束时间" lay-key="24">
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="layui-tab-item" id="now_month">
                          <div id="zanwu" style="height:250px;padding-top:20px;">暂无配置</div>
                          <div id="hasData">
                            <div class="layui-form-item">
                                <label class="layui-form-label">流水:</label>
                                <div class="layui-input-block">
                                    <div class="liushui" style="padding-top: 6px;"></div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">额度:</label>
                                <div class="layui-input-block">
                                    <input type="number" placeholder="请输入额度" class="layui-input quota">
                                </div>
                            </div>
                            <div class="layui-form-item">
                              <label class="layui-form-label">开始时间:</label>
                              <div class="layui-input-block">
                                <input type="text" style="border-radius:5px" class="layui-input start-item test-item" placeholder="开始时间" lay-key="25">
                              </div>
                            </div>
                            <div class="layui-form-item">
                              <label class="layui-form-label">结束时间:</label>
                              <div class="layui-input-block">
                                <input type="text" style="border-radius:5px" class="layui-input end-item2 test-item" placeholder="结束时间" lay-key="26">
                              </div>
                            </div>
                            <div class="layui-form-item">
                              <div class="layui-input-block">
                                  <div class="layui-footer" style="left: 0;">
                                      <button class="layui-btn now_config_submit">确定</button>
                                  </div>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="layui-tab-item" id="next_month">
                          <div id="zanwu" style="height:250px;padding-top:20px;">暂无配置</div>
                          <div id="hasData">
                            <div class="layui-form-item">
                                <label class="layui-form-label">流水:</label>
                                <div class="layui-input-block">
                                    <div class="liushui" style="padding-top: 6px;"></div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">额度:</label>
                                <div class="layui-input-block">
                                    <input type="number" placeholder="请输入额度" class="layui-input quota">
                                </div>
                            </div>
                            <div class="layui-form-item">
                              <label class="layui-form-label">开始时间:</label>
                              <div class="layui-input-block">
                                <input type="text" style="border-radius:5px" class="layui-input start-item test-item" placeholder="开始时间" lay-key="27">
                              </div>
                            </div>
                            <div class="layui-form-item">
                              <label class="layui-form-label">结束时间:</label>
                              <div class="layui-input-block">
                                <input type="text" style="border-radius:5px" class="layui-input end-item3 test-item" placeholder="结束时间" lay-key="28">
                              </div>
                            </div>
                            <div class="layui-form-item">
                              <div class="layui-input-block">
                                  <div class="layui-footer" style="left: 0;">
                                      <button class="layui-btn config_submit">确定</button>
                                  </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="layui-col-md6">
                    <table id="configStorelistTable" lay-filter="configStorelistTable"></table>
                  </div>
                </div>
                
                
            </div>
        </div>
        <input type="hidden" id="id">
        <input type="hidden" id="now_id">
    </div>
      <div id="open_import_all" class="hide" style="display: none;background-color: #fff;">
          <div class="layui-card-body" style="margin-left: 75px;">
              <div class="layui-form">
                  <div class="layui-form-item" >
                      <form id= "uploadForm" >
                          <div class="layui-btn uploadFile" style="margin-right:20px;">选择所需上传文件</div>
                          <input type="file" name="file" id="file" style="display: none;"/>
                          <input type="button" value="确定" id="Upload-All" class="layui-btn"/>
                      </form>
                  </div>
              </div>
          </div>
      </div>
    <div id="open_import" class="hide" style="display: none;background-color: #fff;">
      <div class="layui-card-body" style="margin-left: 75px;">
        <div class="layui-form">
          <div class="layui-form-item">
              <label class="layui-form-label">通道名称:</label>
              <div class="layui-input-block">
                  <div class="name" style="padding-top: 6px;"></div>
              </div>
          </div>
          <div class="layui-form-item">
              <label class="layui-form-label">通道标识:</label>
              <div class="layui-input-block">
                  <div class="code" style="padding-top: 6px;"></div>
              </div>
          </div>
          <div class="layui-form-item">
              <label class="layui-form-label">开始时间:</label>
              <div class="layui-input-block">
                <input type="text" style="border-radius:5px" class="layui-input start_date" placeholder="开始时间" lay-key="29">
              </div>
          </div>
          <div class="layui-form-item">
              <label class="layui-form-label">结束时间:</label>
              <div class="layui-input-block">
                <input type="text" style="border-radius:5px" class="layui-input end_date" placeholder="结束时间" lay-key="30">
              </div>
          </div>
          <div class="layui-form-item" >
            <form id= "uploadForm" >            
              <div class="layui-btn uploadFile" style="margin-right:20px;">选择所需上传文件</div>                  
              <input type="file" name="file" id="file" style="display: none;"/> 
              <input type="button" value="确定上传" id="Upload" class="layui-btn"/>  
            </form>
          </div>
        </div>
      </div>
    </div>
    <div id="import_list" class="hide" style="display: none; background-color: #fff;">
      <div class="layui-card-body" style="height: 576px;">
        <div style="display:flex;margin:10px 0">
          <span>通道名称：</span><div class="name"></div>
        </div>
        <div style="display:flex;margin:10px 0">
          <span>通道标识：</span><div class="code"></div>
        </div>
        <div>
          <table id="importlistTable" lay-filter="importlistTable"></table>
          <script type="text/html" id="importtable-content-list">
            <a class="layui-btn layui-btn-normal layui-btn-xs download" lay-event="download">下载</a>
          </script>
        </div>
      </div>
    </div>
    <div id="store_list" class="hide" style="display: none; background-color: #fff;">
      <div class="layui-card-body">
        <div style="display:flex;margin:10px 0">
          <span>通道标识：</span><div class="code"></div>
        </div>
        <div style="display:flex;margin:10px 0">
          <span>商户号：</span><div class="mch_id"></div>
        </div>
        <div>
          <table id="storelistTable" lay-filter="storelistTable"></table>
        </div>
      </div>
    </div>
      <div id="company_list" class="hide" style="display: none; background-color: #fff; width: 516px; height: 450px;padding-top:10px">
          <div class="layui-input-block" style="color: red">
              数据较多，最多选择5个。
          </div>
          <label class="layui-form-label" style="text-align:center">通道</label>
          <div class="layui-input-block" style="margin-right: 10px;">
              <select name="company" id="company" xm-select="company" xm-select-max="5">
              </select>
          </div>
          <div class="layui-form-item">
              <div style="margin-top: 310px;text-align: center;">
                  <div class="layui-footer" style="left: 0;">
                      <button class="layui-btn compay_submit">确定</button>
                  </div>
              </div>
          </div>
      </div>
    <!-- 一键导入错误列表 -->
    <div id="error_list" class="hide" style="display: none; background-color: #fff;">
      <div class="layui-card-body">
        <div style="display:flex;margin:10px 0;text-align:center">
          <span>失败</span><div class="error_total" style="color:#ff594f"></div><span>个</span>
        </div>
        <div>
          <table id="errorlistTable" lay-filter="errorlistTable"></table>
        </div>
      </div>
    </div>
    <!-- 易生支付a获取额度 -->
    <div id="get_quato" class="hide" style="display: none;background-color: #fff;">
        <div class="layui-card-body" style="padding: 15px;">
            <div class="layui-form">
                <div class="layui-form-item">
                    <label class="layui-form-label">商户号:</label>
                    <div class="layui-input-block">
                        <input type="text" placeholder="请输入" class="layui-input registrationId">
                    </div>
                    <div style="font-size:14px;color:red;margin:12px 0;margin-left:110px">输入多个商户号请用英文逗号分隔</div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <div class="layui-footer" style="left: 0;">
                            <button class="layui-btn getQuatoSubmit">确定</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <input type="hidden" id="id">
    </div>
    <!-- 民生联合收单获取额度 -->
    <div id="get_cmbc_union_quato" class="hide" style="display: none;background-color: #fff;">
        <div class="layui-card-body" style="padding: 15px;">
            <div class="layui-form">
                <div class="layui-form-item">
                    <label class="layui-form-label">商户号:</label>
                    <div class="layui-input-block">
                        <input type="text" placeholder="请输入" class="layui-input registrationId">
                    </div>
                    <div style="font-size:14px;color:red;margin:12px 0;margin-left:110px">输入多个商户号请用英文逗号分隔</div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">活动编码:</label>
                    <div class="layui-input-block">
                        <input type="text" placeholder="请输入" class="layui-input act_code">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <div class="layui-footer" style="left: 0;">
                            <button class="layui-btn getCmbcunionQuatoSubmit">确定</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <input type="hidden" id="id">
    </div>
    <!-- 易生支付a/民生联合收单 -->
    <div id="quato_config" class="hide" style="display: none;background-color: #fff;top: '50%',transform:'translateY(-50%)'">
      <div class="layui-card-body" style="padding: 15px;">
        <table id="quatoConfigTable" lay-filter="quatoConfigTable"></table>
        <script type="text/html" id="configtable-content-list">
          <a class="layui-btn layui-btn-normal layui-btn-xs shangchuan" lay-event="shangchuan">上传</a>
        </script>
        <script type="text/html" id="selBankConfig">
          <div class="layui-input-inline">
            <select name="selBank" id="selBank" lay-filter="selBank">
              <!-- <option value=""></option>
              <option value="1">易生浙商银行</option>
              <option value="2">易生杭州银行</option> -->
            </select>
          </div>
        </script>
      </div>
    </div>
  </div>
  <!-- 导入确认弹框表格 -->
  <div id="exportTable" class="hide" style="display: none; background-color: #fff;padding: 15px">
    <table id="previewTable" lay-filter="previewTable"></table>

    <!-- 操作列模板 -->
    <script type="text/html" id="operateTpl">
        @{{# if(d.uploaded){ }}
            <button class="layui-btn layui-btn-xs layui-btn-disabled" disabled>已上传</button>
        @{{# } else { }}
            <button class="layui-btn layui-btn-xs" lay-event="sendClick">上传</button>
        @{{# } }}
    </script>
  </div>

  <input type="hidden" class="compayArr" value="">
  <script src="{{asset('/layuiadmin/layui/layui.js')}}"></script>
  <script type="text/javascript" src="{{asset('/school/js/xlsx.full.min.js')}}"></script>
  <script>
    var token = localStorage.getItem("Usertoken");
    layui.config({
      base: '../../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index','form', 'table','laydate','tree', 'formSelects'], function(){
        var $ = layui.$
            ,admin = layui.admin
            ,table = layui.table
            ,form = layui.form
            ,laydate = layui.laydate
            ,element = layui.tree
            ,formSelects = layui.formSelects;

        // 未登录,跳转登录页面
        $(document).ready(function(){        
            if(token==null){
                window.location.href="{{url('/user/login')}}"; 
            }
        });
        var arr=[];
        var companyMerList;
        formSelects.config('company', {
            beforeSuccess: function(id, url, searchVal, result){


                    //我要把数据外层的code, msg, data去掉
                result = result.data;

//                console.log(result);
                for(var i=0;i<result.length;i++){
                    var data ={"value":result[i].code,"name":result[i].name};
                    arr.push(data);
                    // console.log(arr);
                }
               console.log(arr);
                //然后返回数据
                return arr;
            }
        }).data('company', 'server', {
            url:"{{url('/api/user/company_lists?token=')}}"+token
        });
        var arra=[];
        formSelects.on('company', function(id, vals, val, isAdd, isDisabled){

            // var maxCount = 5; // 设定最多选择数量
            // if(val.length > maxCount){
            //     // 如果选择的数量超过了最大限制，则移除最前面的选中项
            //     val.splice(0, val.length - maxCount);
            //     // 更新多选框的选中状态
            //     formSelects.checked('company', val.value);
            //     // 弹窗提示用户
            //     layer.msg('最多只能选择' + maxCount + '个选项。');
            // }
            if(isAdd==true){
                if(!arra.includes(val.value)){
                  arra.push(val.value);
                }
            }else{
              if(arra.includes(val.value)){
                arra = arra.filter(item => item !== val.value);
              }
            }
            $('.compayArr').val(arra.join());
        });


        var curCompany = {}
        var companyList = [];
        $.post("{{url('/api/user/company_lists')}}",
        {
            token:token
            ,return_type:'layui'
        },function(res){
          
          if(res.data && res.data.length>0){
            //进来默认不加载
            // $('.tongdao_name span').html(res.data[0].name);
            // $('.shanghuhao span').html(res.data[0].code);
            // if(res.data[0].code && res.data[0].code == 'easypaya'){
            //   $('#getquota').show()
            // }else{
            //   $('#getquota').hide()
            // }
            // curCompany = res.data[0];
            companyList = res.data;
            let html = ''
            for(var i=0;i<res.data.length;i++){
              let classname = 'companylist'
              // if(i===0){
              //   classname = 'companylist companyActive'
              // }else{
              //   classname = 'companylist'
              // }
              html += `<li><div class="${classname}" data-index="${i}">
              <img src="{{asset('/school/images/bank.png')}}" style="width: 18px;height: 18px;margin-right: 4px;vertical-align: sub;">
              ${res.data[i].name}</div></li>`
            }
            $('#demo').html(html)
            //进来默认不加载
            // getTableData(res.data[0].code)



          }
          // layui.tree({
          //       elem: '#demo'
          //       ,nodes: res.data
          //       ,click: function(node){
          //             console.log(node); //node即为当前点击的节点数据
          //           $('.tongdao_name span').html(node.name);
          //           $('.shanghuhao span').html(node.code);
          //           curCompany = {...node};
          //           getTableData(node.code) 
          //       }
          //   });
          //   getTableData(res.data[0].code) 
        },"json")
        
        $('#demo').on('click', '.companylist', function() {
            $(this).addClass('companyActive');
            $(this).siblings().removeClass('companyActive');
            let dataindex = $(this).data('index')
            let node = companyList[dataindex]
            curCompany = node;
            $('.tongdao_name span').html(node.name);
            $('.shanghuhao span').html(node.code);
            if(node.code && (node.code == 'easypaya' || node.code == 'cmbcunion' || node.code == 'gtxy')){
              $('#getquota').show()
            }else{
              $('#getquota').hide()
            }
            curCompany = {...node};
            getTableData(node.code)
            let classList = $('#demo .companylist');
            for(var i=0;i<classList.length;i++){
              if(i !== dataindex){
                $('#demo .companylist').eq(i).removeClass('companyActive');
              }
            }
        })

        // 进来默认不加载
        table.render({
          elem: '#test-table-page'
          ,url: ""
          ,method: 'post'
          ,where:{
            token:token,
          }
          ,request:{
            pageName: 'p', 
            limitName: 'l'
          }
          ,page: true
          ,limit: 2000 // 设置每页显示10条记录
          ,cellMinWidth: 150
          ,height:500
          ,cols: [[
              {field:'mch_id', title: '商户号'}
              , {field:'quota', title: '额度', sort:true}
              , {field:'no_use_quota', title: '未使用额度' , sort:true}
              ,{width:200,align:'center', fixed: 'right', toolbar: '#table-content-list',title: '操作'}
          ]]
          ,response: {
              statusName: 'status' //数据状态的字段名称，默认：code
              ,statusCode: 1 //成功的状态码，默认：0
              ,msgName: 'message' //状态信息的字段名称，默认：msg
              ,countName: 't' //数据总数的字段名称，默认：count
              ,dataName: 'data' //数据列表的字段名称，默认：data
            } 
            ,scroll: { // 开启横向滚动条
              y: 500 // 横向滚动区域宽度，跟容器宽度一样
            }
          ,done: function(res, curr, count){
            $('th').css({'font-weight': 'bold', 'font-size': '15','color': 'black','background':'linear-gradient(#f2f2f2,#cfcfcf)'});	//进行表头样式设置
          }
        })
        
        function getTableData(code){
          var loading = layer.msg('数据请求中..', {
            icon: 16
            ,shade: 0.3
            ,time: false
          });
          table.render({
              elem: '#test-table-page'
              ,url: "{{url('/api/user/company_merchant_lists')}}"
              ,method: 'post'
              ,where:{
                token:token,
                code
              }
              ,request:{
                pageName: 'p', 
                limitName: 'l'
              }
              ,page: true
              ,limit: 2000 // 设置每页显示10条记录
              ,cellMinWidth: 150
              ,height:500
              ,cols: [[
                  {field:'mch_id', title: '商户号'}
                  , {field:'quota', title: '额度', sort:true}
                  , {field:'no_use_quota', title: '未使用额度' , sort:true}
                  ,{width:200,align:'center', fixed: 'right', toolbar: '#table-content-list',title: '操作'}
              ]]
              ,response: {
                  statusName: 'status' //数据状态的字段名称，默认：code
                  ,statusCode: 1 //成功的状态码，默认：0
                  ,msgName: 'message' //状态信息的字段名称，默认：msg
                  ,countName: 't' //数据总数的字段名称，默认：count
                  ,dataName: 'data' //数据列表的字段名称，默认：data
                } 
                ,scroll: { // 开启横向滚动条
                  y: 500 // 横向滚动区域宽度，跟容器宽度一样
                }
              ,done: function(res, curr, count){
                companyMerList = res.data || [];
                $('th').css({'font-weight': 'bold', 'font-size': '15','color': 'black','background':'linear-gradient(#f2f2f2,#cfcfcf)'});	//进行表头样式设置
                layer.close(loading);
              }
          });
        }
        
        $("#addcompany").click(function(){
            layer.open({
                type: 1,
                title: false,
                closeBtn: 1,
                area: '516px',
                title:'导入额度',
                skin: 'layui-layer-nobg', //没有背景色
                shadeClose: true,
                content: $('#open_import_all'),
                cancel: function(layero,index){
                    layer.closeAll();
                }
            });
        });
        $("#download-mch-bet").click(function(){
            layer.open({
                type: 1,
                title: false,
                closeBtn: 1,
                area: '516px',
                title:'选择通道',
                skin: 'layui-layer-nobg', //没有背景色
                shadeClose: true,
                content: $('#company_list'),
                cancel: function(layero,index){
                    layer.closeAll();
                }
            });
        });
        $(".compay_submit").click(function(){
            //执行重载
            var pageLoading = layer.msg('数据请求中..', {
                icon: 16
                ,shade: 0.3
                ,time: false
            });
            var code = $('.compayArr').val();

            $.ajax({
                url : "{{url('/api/user/company_download_mch')}}",
                data : {
                    token:token,
                    code:code
                },
                type : 'post',
                success : function(data) {
                    if (data.status == 1) {
                        layer.close(pageLoading);
                        let urls = data.data.url.replace(/http:\/\//i, 'https://');
                        window.location.href=urls;
                    } else {
                        alert(data.message);
                    }
                    // window.location.href=
                },
                error : function(data) {
                    alert('查找板块报错');
                }
            });

        });

        $("#editcompany").click(function(){
          console.log(curCompany,'curCompany-----')
          $('#add_edit #id').val(curCompany.id);
          $('#add_edit .name').val(curCompany.name);
          $('#add_edit .quota_date').val(curCompany.quota_date);
          $('#add_edit .limit_money').val(curCompany.limit_money);
          $('#add_edit .sort').val(curCompany.sort);
          $('#add_edit .code').val(curCompany.code);
          $("#add_edit .code").attr("disabled", "disabled");
          layer.open({
              type: 1,
              title: false,
              closeBtn: 1,
              title: '编辑通道',
              area: '516px',
              skin: 'layui-layer-nobg', //没有背景色
              shadeClose: true,
              content: $('#add_edit'),
              cancel: function(layero,index){
                    layer.closeAll();
                }
          });
        });

        $('.submit').click(function(){
                $.post("{{url('/api/user/company_edit')}}",
                {
                    id:$('#add_edit #id').val(),
                    token:token,
                    name:$('#add_edit .name').val(),
                    quota_date:$('#add_edit .quota_date').val(),
                    limit_money:$('#add_edit .limit_money').val(),
                    sort:$('#add_edit .sort').val(),
                    code:$('#add_edit .code').val(),
                },function(res){
                    if(res.status>0){
                        layer.msg(res.message, {
                            offset: '50px'
                            ,icon: 1
                            ,time: 1000
                        },function(){
                          // window.location.reload();
                          layer.closeAll();
                          $.post("{{url('/api/user/company_lists')}}",
                            {
                                token:token
                                ,return_type:'layui'
                            },function(res){
                              
                              if(res.data && res.data.length>0){
                                companyList = res.data;
                                let html = ''
                                for(var i=0;i<res.data.length;i++){
                                  let classname = ''
                                  if(res.data[i].id === curCompany.id){
                                    classname = 'companylist companyActive'
                                    $('.tongdao_name span').html(res.data[i].name);
                                    $('.shanghuhao span').html(res.data[i].code);
                                    if(res.data[i].code && (res.data[i].code == 'easypaya' || res.data[i].code == 'cmbcunion' || res.data[i].code == 'gtxy')){
                                      $('#getquota').show()
                                    }else{
                                      $('#getquota').hide()
                                    }
                                    curCompany = res.data[i]
                                  }else{
                                    classname = 'companylist'
                                  }
                                  html += `<li><div class="${classname}" data-index="${i}">
                                  <img src="{{asset('/school/images/bank.png')}}" style="width: 18px;height: 18px;margin-right: 4px;vertical-align: sub;">
                                  ${res.data[i].name}</div></li>`
                                }
                                $('#demo').html(html)
                                getTableData(curCompany.code) 
                              }
                            },"json")
                        });
                    }else{
                        layer.msg(res.message, {
                            offset: '50px'
                            ,icon: 2
                            ,time: 1000
                        });
                    }
                }, "json");
            });

        table.on('tool(test-table-page)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
          var e = obj.data; //获得当前行数据
          var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
          var tr = obj.tr; //获得当前行 tr 的DOM对象
//          console.log(e);
          // localStorage.setItem('s_store_id', e.store_id);

          if(layEvent === 'config'){
            //配置
            $.post("{{url('/api/user/company_merchant_quota_config')}}",
            {
                token:token,
                code:curCompany.code,
                mch_id:e.mch_id
            },function(res){
              console.log(res,'peizhi-----')
              $('#config_model .code').html(curCompany.code)
              $('#config_model .mch_id').html(e.mch_id)
              if(res.status == 1){
                $('#config_model .last_title').html(res.data.last_title || '')
                $('#config_model .now_title').html(res.data.now_title || '')
                $('#config_model .next_title').html(res.data.next_title || '')
                let last_month = res.data.last_month
                let now_month = res.data.now_month
                let next_month = res.data.next_month
                if(last_month){
                  console.log(last_month.start_date,last_month.start_date.toString().substring(0,4),'last_month.start_date')
                  let start_date = last_month.start_date.toString().substring(0,4) + '-' + last_month.start_date.toString().substring(4,6)+  '-' + last_month.start_date.toString().substring(6,8)
                  let end_date = last_month.end_date.toString().substring(0,4) + '-' + last_month.end_date.toString().substring(4,6)+  '-' + last_month.end_date.toString().substring(6,8)
                  $('#config_model #last_month .start-item').val(start_date);
                  $('#config_model #last_month .end-item').val(end_date);
                  $('#config_model #last_month .quota').val(last_month.quota);
                  $('#config_model #last_month .liushui').html(last_month.total_amount);
                  $("#config_model #last_month .start-item").attr("disabled", "disabled");
                  $("#config_model #last_month .end-item").attr("disabled", "disabled");
                  $("#config_model #last_month .quota").attr("disabled", "disabled");
                  $('#config_model #last_month #zanwu').hide()
                  $('#config_model #last_month #hasData').show()
                }else{ //没有值
                  $('#config_model #last_month #zanwu').show()
                  $('#config_model #last_month #hasData').hide()
                }
                if(now_month){
                  $('#config_model #now_id').val(now_month.id || '')
                  let start_date = now_month.start_date.toString().substring(0,4) + '-' + now_month.start_date.toString().substring(4,6)+  '-' + now_month.start_date.toString().substring(6,8)
                  let end_date = now_month.end_date.toString().substring(0,4) + '-' + now_month.end_date.toString().substring(4,6)+  '-' + now_month.end_date.toString().substring(6,8)
                  $('#config_model #now_month .start-item').val(start_date);
                  $('#config_model #now_month .end-item2').val(end_date);
                  $('#config_model #now_month .quota').val(now_month.quota);
                  $('#config_model #now_month .liushui').html(now_month.total_amount);
                  // $("#config_model #now_month .start-item").attr("disabled", "disabled");
                  // $("#config_model #now_month .end-item2").attr("disabled", "disabled");
                  // $("#config_model #now_month .quota").attr("disabled", "disabled");
                  $('#config_model #now_month #zanwu').hide()
                  $('#config_model #now_month #hasData').show()
                }else{ //没有now_month
                  $('#config_model #now_month #zanwu').show()
                  $('#config_model #now_month #hasData').hide()
                  $('#config_model #now_id').val('')
                }
                $('#config_model #next_month #zanwu').hide()
                $('#config_model #next_month #hasData').show()
                if(next_month){
                  $('#config_model #id').val(next_month.id || '')
                  let start_date = next_month.start_date.toString().substring(0,4) + '-' + next_month.start_date.toString().substring(4,6)+  '-' + next_month.start_date.toString().substring(6,8)
                  let end_date = next_month.end_date.toString().substring(0,4) + '-' + next_month.end_date.toString().substring(4,6)+  '-' + next_month.end_date.toString().substring(6,8)
                  $('#config_model #next_month .start-item').val(start_date);
                  $('#config_model #next_month .end-item3').val(end_date);
                  $('#config_model #next_month .quota').val(next_month.quota);
                  $('#config_model #next_month .liushui').html(next_month.total_amount);
                }else{
                  $('#config_model #id').val('')
                }
              }
              layer.open({
                type: 1,
                title: false,
                closeBtn: 1,
                title: '通道配置',
                area: '1000px',
                skin: 'layui-layer-nobg', //没有背景色
                shadeClose: true,
                content: $('#config_model'),
                cancel: function(layero,index){
                    layer.closeAll();
                    $('#config_model #last_month .start-item').val('');
                    $('#config_model #last_month .end-item').val('');
                    $('#config_model #last_month .quota').val('');
                    $('#config_model #last_month .liushui').val('');
                    $('#config_model #now_month .start-item').val('');
                    $('#config_model #now_month .end-item2').val('');
                    $('#config_model #now_month .quota').val('');
                    $('#config_model #now_month .liushui').val('');
                    $('#config_model #next_month .start-item').val('');
                    $('#config_model #next_month .end-item3').val('');
                    $('#config_model #next_month .quota').val('');
                    $('#config_model #next_month .liushui').html('');
                    console.log(1121111111,'cancel')
                },
                success: function(layero, index) {
                  table.render({
                    elem: '#configStorelistTable'
                    ,height:480
                    ,url: "{{url('/api/user/company_store_list')}}"
                    ,method: 'get'
                    ,where:{
                        token:token,
                        company_code:curCompany.code,
                        mch_id:e.mch_id
                    }
                    ,request:{
                        pageName: 'p',
                        limitName: 'l'
                    }
                    ,page: true
                    ,cols: [[
                        {field: 'store_id', title: '门店id',width:200}
                        ,{field: 'store_name',  title: '门店名称',}
                    ]]
                    ,response: {
                        statusName: 'status' //数据状态的字段名称，默认：code
                        ,statusCode: 1 //成功的状态码，默认：0
                        ,msgName: 'message' //状态信息的字段名称，默认：msg
                        ,countName: 't' //数据总数的字段名称，默认：count
                        ,dataName: 'data' //数据列表的字段名称，默认：data
                    }
                    ,done: function(res, curr, count){
                        $('th').css({'font-weight': 'bold', 'font-size': '15','color': 'black','background':'#fff'});	//进行表头样式设置
                    }
                  });
                }
            });
            },"json")
          }else if(layEvent === 'storelist'){
            $('#store_list .code').html(curCompany.code);
            $('#store_list .mch_id').html(e.mch_id);
            table.render({
                elem: '#storelistTable'
                ,height:480
                ,url: "{{url('/api/user/company_store_list')}}"
                ,method: 'get'
                ,where:{
                    token:token,
                    company_code:curCompany.code,
                    mch_id:e.mch_id
                }
                ,request:{
                    pageName: 'p',
                    limitName: 'l'
                }
                ,page: true
                ,cols: [[
                    {field: 'store_id', title: '门店id',width:200}
                    ,{field: 'store_name',  title: '门店名称',}
                ]]
                ,response: {
                    statusName: 'status' //数据状态的字段名称，默认：code
                    ,statusCode: 1 //成功的状态码，默认：0
                    ,msgName: 'message' //状态信息的字段名称，默认：msg
                    ,countName: 't' //数据总数的字段名称，默认：count
                    ,dataName: 'data' //数据列表的字段名称，默认：data
                }
                ,done: function(res, curr, count){
                    $('th').css({'font-weight': 'bold', 'font-size': '15','color': 'black','background':'linear-gradient(#f2f2f2,#cfcfcf)'});	//进行表头样式设置
                }
              });
              layer.open({
                  type: 1,
                  title: '门店列表',
                  closeBtn: 1,
                  area: '516px',
                  skin: 'layui-layer-nobg', //没有背景色
                  shadeClose: true,
                  content: $('#store_list'),
                  cancel: function(layero,index){
                    layer.closeAll();
                  }
              });
          }

        });
        //配置提交
        $('.config_submit').click(function(){
              let starttime = $('#config_model #next_month .start-item').val();
              let starts = starttime ? starttime.replace(/-/g, "") :'';
              let endtime = $('#config_model #next_month .end-item3').val();
              let ends = endtime ? endtime.replace(/-/g, "") :'';
                $.post("{{url('/api/user/company_merchant_quota_add')}}",
                {
                  mch_id:$('#config_model .mch_id').html(),
                  token:token,
                  company_rule_id:curCompany.id,
                  company_code:$('#config_model .code').html(),
                  start_date:starts,
                  end_date:ends,
                  quota:$('#config_model #next_month .quota').val(),
                  id:$('#config_model #id').val()
                },function(res){
                    if(res.status>0){
                        layer.closeAll();
                        layer.msg(res.message, {
                            offset: '50px'
                            ,icon: 1
                            ,time: 1000
                        },function(){
                          $('#config_model #last_month .start-item').val('');
                          $('#config_model #last_month .end-item').val('');
                          $('#config_model #last_month .quota').val('');
                          $('#config_model #last_month .liushui').html('');
                          $('#config_model #now_month .start-item').val('');
                          $('#config_model #now_month .end-item2').val('');
                          $('#config_model #now_month .quota').val('');
                          $('#config_model #now_month .liushui').html('');
                          $('#config_model #next_month .start-item').val('');
                          $('#config_model #next_month .end-item3').val('');
                          $('#config_model #next_month .quota').val('');
                          $('#config_model #next_month .liushui').html('');
                        });
                    }else{
                        layer.msg(res.message, {
                            offset: '50px'
                            ,icon: 2
                            ,time: 1000
                        });
                    }
                    
                }, "json");
            });

        //本月配置提交
        $('.now_config_submit').click(function(){
              let starttime = $('#config_model #now_month .start-item').val();
              let starts = starttime ? starttime.replace(/-/g, "") :'';
              let endtime = $('#config_model #now_month .end-item2').val();
              let ends = endtime ? endtime.replace(/-/g, "") :'';
                $.post("{{url('/api/user/company_merchant_quota_add')}}",
                {
                  mch_id:$('#config_model .mch_id').html(),
                  token:token,
                  company_rule_id:curCompany.id,
                  company_code:$('#config_model .code').html(),
                  start_date:starts,
                  end_date:ends,
                  quota:$('#config_model #now_month .quota').val(),
                  id:$('#config_model #now_id').val()
                },function(res){
                    if(res.status>0){
                        layer.closeAll();
                        layer.msg(res.message, {
                            offset: '50px'
                            ,icon: 1
                            ,time: 1000
                        },function(){
                          $('#config_model #last_month .start-item').val('');
                          $('#config_model #last_month .end-item').val('');
                          $('#config_model #last_month .quota').val('');
                          $('#config_model #last_month .liushui').html('');
                          $('#config_model #now_month .start-item').val('');
                          $('#config_model #now_month .end-item2').val('');
                          $('#config_model #now_month .quota').val('');
                          $('#config_model #now_month .liushui').html('');
                          $('#config_model #next_month .start-item').val('');
                          $('#config_model #next_month .end-item3').val('');
                          $('#config_model #next_month .quota').val('');
                          $('#config_model #next_month .liushui').html('');
                        });
                    }else{
                        layer.msg(res.message, {
                            offset: '50px'
                            ,icon: 2
                            ,time: 1000
                        });
                    }
                    
                }, "json");
            });
            //本月配置时间
            laydate.render({
              elem: '#now_month .start-item'
              ,type: 'date'
              ,done: function(value){
              }
            });
            laydate.render({
              elem: '#now_month .end-item2'
              ,type: 'date'
              ,ready: function(date){;
            }
              ,done: function(value){
              }
            });

        laydate.render({
          elem: '#next_month .start-item'
          ,type: 'date'
          ,done: function(value){
          }
        });
        laydate.render({
          elem: '#next_month .end-item3'
          ,type: 'date'
          ,ready: function(date){;
        }
          ,done: function(value){
          }
        });

        //导入额度-开始时间与结束时间
         // 设置开始日期为今天
        var todaydate = new Date();
        var today = todaydate.getFullYear() + '-' + (todaydate.getMonth() + 1) + '-' + todaydate.getDate();
        var startDate = laydate.render({
          elem: '#open_import .start_date'
          ,type: 'date'
          // ,min: today // 设置最小日期为今天
          ,done: function(value,date){
            // if(startDate){ // 如果选择了开始日期
            //   // 设置结束日期的最小值为开始日期+31天
            //   endDate.config.min={
            //     year:date.year,
            //     month:date.month,//关键
            //     date:date.date,
            //   };
            // }
            console.log(value,date,'-------')
          }
        });
        var endDate = laydate.render({
          elem: '#open_import .end_date'
          ,type: 'date'
          // ,min: today // 设置最小日期为今天
          ,done: function(value,date){
            console.log(value,date,'-------')
            // if(endDate){
            //   startDate.config.max={
          // 		  year:date.year,
        	//     	month:date.month-1,//关键
            //     date:date.date,
            //   }
            // }
          }
        });

        $('.import').click(function(){
          $('#open_import .name').html(curCompany.name)
          $('#open_import .code').html(curCompany.code)
          $('#open_import .start_date').val('')
          $('#open_import .end_date').val('')
          layer.open({
            type: 1,
            title: false,
            closeBtn: 1,
            area: '516px',
            title:'导入额度',
            skin: 'layui-layer-nobg', //没有背景色
            shadeClose: true,
            content: $('#open_import'),
            cancel: function(layero,index){
                layer.closeAll();
            }
          });
        });

        // 导入商户
        $('.uploadFile').click(function(){
          console.log('00')
          $("#file").click();
        })
        // 获取文件名
        var file = $('#file');
        var filelist = [];
        file.on('change', function( e ){
            //e.currentTarget.files 是一个数组，如果支持多个文件，则需要遍历
            var name = e.currentTarget.files[0].name;
            filelist = e.currentTarget.files;
            console.log( name );
            console.log(  e.currentTarget.files );
            $('.uploadFile').html(name);
        });
        // excel文件导入
        var tableData = [];
        $('#Upload-All').click(function() {
            // var formData = new FormData($("#uploadForm")[0]);
            // let start_date = $('#open_import .start_date').val();
            // let end_date = $('#open_import .end_date').val();
            // let starts = start_date ? start_date.replace(/-/g, "") : '';
            // let ends = end_date ? end_date.replace(/-/g, "") : '';
            // console.log(formData);
            // $.ajax({
            //     url: "{{url('/api/user/company_import_quota_all?token=')}}" + token,
            //     type: 'POST',
            //     data: formData,
            //     async: false,
            //     cache: false,
            //     contentType: false,
            //     processData: false,
            //     success: function (res) {
            //         console.log(res);
            //         layer.closeAll();
            //         if (res.status > 0) {
            //             if(res.data.error_list && res.data.error_list.length>0){
            //               $('#error_list .error_total').html(res.data.error)
            //               let errorData = []
            //               res.data.error_list.forEach(ele => {
            //                 errorData.push({
            //                   code:ele[0],
            //                   mch_id:ele[1]
            //                 })
            //               });
            //               table.render({
            //                   elem: '#errorlistTable'
            //                   ,height:480
            //                   ,page: false
            //                   ,cols: [[
            //                       {field: 'code', title: '标识',width:240}
            //                       ,{field: 'mch_id',  title: '商户号',width:240}
            //                   ]]
            //                   ,data:errorData
            //                   ,done: function(res, curr, count){
            //                       $('th').css({'font-weight': 'bold', 'font-size': '15','color': 'black','background':'linear-gradient(#f2f2f2,#cfcfcf)'});	//进行表头样式设置
            //                   }
            //                 });
            //               layer.open({
            //                 type: 1,
            //                 title: false,
            //                 closeBtn: 1,
            //                 area: '516px',
            //                 title:'错误列表',
            //                 skin: 'layui-layer-nobg', //没有背景色
            //                 shadeClose: true,
            //                 content: $('#error_list'),
            //                 cancel: function(layero,index){
            //                     layer.closeAll();
            //                 }
            //               });
            //             }else{
            //               layer.msg(res.message, {
            //                 offset: '50px'
            //                 , icon: 1
            //                 , time: 2000
            //               }, function () {
            //                   //执行重载
            //                   table.reload('test-table-page', {
            //                       page: {
            //                           curr: 1
            //                       },
            //                       where: {}
            //                   });
            //               });
            //             }
            //         } else {
            //             layer.alert(res.message, {icon: 2});

            //         }

            //     },
            //     error: function (res) {
            //         layer.msg(res.message, {
            //             offset: '50px'
            //             , icon: 2
            //             , time: 3000
            //         });

            //     }
            // });

            //导入确认弹框
            var uploadFile = filelist[0];
            if(!uploadFile) return;
            console.log(uploadFile,'uploadFile----')
            var reader = new FileReader();
            var headers = [];
            reader.onload = function(e) {
              var extension = uploadFile.name.split('.').pop().toLowerCase();
              const headerMap = {
                '商户号':'mch_id',
                '标识':'code',
                '开始时间':'start_date',
                '结束时间':'end_date',
                '额度':'quota',
              }
              if (extension === 'xlsx' || extension === 'xls' || extension === 'csv') {
                let data = new Uint8Array(e.target.result);
                let workbook = XLSX.read(data, {type: 'array'});
                
                // 获取第一个工作表的数据
                let firstSheet = workbook.Sheets[workbook.SheetNames[0]];
                let jsonData = XLSX.utils.sheet_to_json(firstSheet, {header:1});
                
                // 转换表头和数据
                headers = jsonData[0];
                tableData = jsonData.slice(1).map(function(row,index){
                    var obj = {
                      indexData: index+1, // 生成唯一ID
                      uploaded: false           // 上传状态
                    };
                    headers.forEach(function(header, index){
                      const enField = headerMap[header] || header; // 保留未映射的原始字段
                      obj[enField] = row[index];
                    });
                    return obj;
                });
              } else {
                  layer.msg('仅支持上传 XLSX/XLS 或 CSV 文件');
                  return;
              }
                // 创建弹窗展示表格
                layer.open({
                    type: 1,
                    title: '导入数据预览',
                    area:  ['900px', '600px'],
                    content: $('#exportTable'),
                    success: function(){
                        // 渲染表格
                        table.render({
                            elem: '#previewTable',
                            data: tableData,
                            cols: [[
                              // 序号列
                              {field: 'indexData', title: '序号', width: 80 },
                              // 数据列
                              ...headers.map(chHeader => ({
                                field: headerMap[chHeader] || chHeader, // 英文字段名
                                title: chHeader // 显示中文标题
                              })),
                              // 操作列
                              {title: '操作', width: 100, toolbar: '#operateTpl'}
                            ]],
                            page: true,
                            limit: 10
                        });
                    }
                });
            };
            reader.readAsArrayBuffer(uploadFile);
        });

        // 监听工具条操作
        table.on('tool(previewTable)', function(obj){
          var data = obj.data;
          var tr = obj.tr; //获得当前行 tr 的DOM对象
          console.log(data,'data----')
          console.log(obj,'obj----')
          if(obj.event === 'sendClick'){
              layer.confirm('确认上传该行数据？', function(index){
                var exportQrLoading = layer.msg('上传中..', {
                    icon: 16
                    ,shade: 0.3
                    ,time: false
                });
                $.post("{{url('/api/user/company_merchant_quota_add')}}",
                {
                  mch_id:data.mch_id,
                  token:token,
                  company_code:data.code,
                  start_date:data.start_date,
                  end_date:data.end_date,
                  quota:data.quota
                },function(result){
                  if (result.status == 1) {
                    layer.msg(result.message, {
                        icon: 1,
                        time: 1000 //1秒关闭（如果不配置，默认是3秒）
                    }, function () {
                        layer.close(exportQrLoading)
                    });
                    // 更新数据状态
                    var targetIndex = tableData.findIndex(
                        item => item.indexData === data.indexData
                    );
                    if(targetIndex > -1){
                      tableData[targetIndex].uploaded = true;
                      // 刷新表格
                      table.reload('previewTable', {
                          data: tableData,
                      });
                    }
                  }
                  else {
                      layer.msg(result.message);
                  }
                }, "json")
              });
          }
        });
        

        $('#Upload').click(function(){
          var formData = new FormData($( "#uploadForm" )[0]); 
          let start_date = $('#open_import .start_date').val();
          let end_date = $('#open_import .end_date').val();
          let starts = start_date ? start_date.replace(/-/g, "") :'';
          let ends = end_date ? end_date.replace(/-/g, "") :'';
          console.log(formData);
          $.ajax({   
            url: "{{url('/api/user/company_import_quota?token=')}}"+token+"&company_rule_id="+curCompany.id+"&company_code="+curCompany.code+"&start_date="+starts+"&end_date="+ends,  
            type: 'POST',  
            data: formData,  
            async: false,  
            cache: false,  
            contentType: false,  
            processData: false,  
            success: function (res) {  
              console.log(res);
              layer.closeAll();
              if(res.status>0){
                layer.msg(res.message, {
                  offset: '50px'
                  ,icon: 1
                  ,time: 2000
                },function(){
                  //执行重载
                  table.reload('test-table-page', {
                      page: {
                          curr: 1
                      },
                      where: {
                      }
                  });
                });
              }else{
                layer.alert(res.message, {icon: 2});

              }
            
            },  
            error: function (res) {  
              layer.msg(res.message, {
                offset: '50px'
                ,icon: 2
                ,time: 3000
              });
                
            }  
        });

        });
        //导入记录
        $('.importlist').click(function(){
          $('#import_list .name').html(curCompany.name);
          $('#import_list .code').html(curCompany.code);

          layer.open({
              type: 1,
              title: '导入记录',
              closeBtn: 1,
              area: ['655px', '640px'],
              offset: 'auto', // 居中显示
              skin: 'layui-layer-nobg', //没有背景色
              shadeClose: true,
              content: $('#import_list'),
              cancel: function(layero,index){
                layer.closeAll();
              },
              success: function(layero, index) {
                table.render({
                  elem: '#importlistTable'
                  ,height:480
                    ,limit: 2000 // 设置每页显示10条记录
                  ,url: "{{url('/api/user/company_import_list')}}"
                  ,method: 'get'
                  ,where:{
                      token:token,
                      company_code:curCompany.code
                  }
                  ,request:{
                      pageName: 'p',
                      limitName: 'l'
                  }
                  ,page: true
                  ,cols: [[
                      {width:80,align:'center', fixed: 'left', toolbar: '#importtable-content-list',title: '操作'}
                      ,{field: 'start_date',  title: '开始时间',width:180,templet:function(info){
                        let start_date = ''
                        if(info.start_date){
                          start_date = info.start_date.toString().substring(0,4) + '-' + info.start_date.toString().substring(4,6)+  '-' + info.start_date.toString().substring(6,8)
                        }
                        return start_date
                      }}
                      ,{field: 'end_date',  title: '结束时间',width:180,templet:function(info){
                        let end_date = ''
                        if(info.end_date){
                          end_date = info.end_date.toString().substring(0,4) + '-' + info.end_date.toString().substring(4,6)+  '-' + info.end_date.toString().substring(6,8)
                        }
                        return end_date
                      }}
                      ,{field: 'created_at',  title: '导入时间',width:180}
                      
                  ]]
                  ,response: {
                      statusName: 'status' //数据状态的字段名称，默认：code
                      ,statusCode: 1 //成功的状态码，默认：0
                      ,msgName: 'message' //状态信息的字段名称，默认：msg
                      ,countName: 't' //数据总数的字段名称，默认：count
                      ,dataName: 'data' //数据列表的字段名称，默认：data
                  }
                  ,done: function(res, curr, count){
                      $('th').css({'font-weight': 'bold', 'font-size': '15','color': 'black','background':'linear-gradient(#f2f2f2,#cfcfcf)'});	//进行表头样式设置
                  }
                });
              }
          });
        })
        //导入记录-下载
        table.on('tool(importlistTable)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
          var e = obj.data; //获得当前行数据
          var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
          var tr = obj.tr; //获得当前行 tr 的DOM对象
//          console.log(e);
          // localStorage.setItem('s_store_id', e.store_id);

          if(layEvent === 'download'){
            if(e.url){
              let urlss = e.url.replace(/http:\/\//i, 'https://');
              window.location.href=urlss;
            }
          }
        })
        //监听搜索
        form.on('submit(LAY-app-contlist-search)', function(data){
              var search_mchid = data.field.search_mchid;
              //console.log(data);
              //执行重载
              table.reload('test-table-page', {
                  page: {
                      curr: 1
                  },
                  where: {
                      mch_id:search_mchid
                  }
              });
        });

        $("#getquota").click(function(){
          // 获取当前日期
          var today = new Date();
          // 获取日期中的日
          var day = today.getDate();
          if(curCompany.code == 'easypaya' || curCompany.code == 'gtxy'){ //易生支付a/国通联合收单
            let isshow = true;
            if(curCompany.code == 'easypaya' && day <= 5){ //易生联合收单 6号之后才能获取
              isshow = false
              layer.msg('需要每月6号及6号之后才能获取额度')
            }
            if(isshow == true){
              // 获取额度
              $('#get_quato .registrationId').val('');
              layer.open({
                type: 1,
                title: false,
                closeBtn: 1,
                title: '获取额度',
                area: '516px',
                skin: 'layui-layer-nobg', //没有背景色
                shadeClose: true,
                content: $('#get_quato'),
                cancel: function(layero,index){
                      layer.closeAll();
                  }
              });
            }
          }else if(curCompany.code == 'cmbcunion'){ //民生联合收单
            if(day > 8){ //9号之后才能获取
              // 获取额度
              $('#get_cmbc_union_quato .registrationId').val('');
              $('#get_cmbc_union_quato .act_code').val('');
              layer.open({
                type: 1,
                title: false,
                closeBtn: 1,
                title: '获取额度',
                area: '516px',
                skin: 'layui-layer-nobg', //没有背景色
                shadeClose: true,
                content: $('#get_cmbc_union_quato'),
                cancel: function(layero,index){
                      layer.closeAll();
                  }
              });
            }else {
              layer.msg('需要每月9号及9号之后才能获取额度')
            }
          }
          
        })

         $('.getQuatoSubmit').click(function(){
            $('.getQuatoSubmit').prop('disabled', true);
            if(curCompany.code == 'gtxy'){
              $.get("{{url('/api/v2/Merchant/Quota/getQuota')}}",
              {
                mch_id:$('#get_quato .registrationId').val(),
                  token:token,
              },function(res){
                  $('.getQuatoSubmit').prop('disabled', false);
                  if(res.status == 1){
                    // layer.msg(res.message);
                      // 打开额度配置弹框
                      let list = res.data || [];
                      quotaConfig(list)
                  }else{
                      layer.msg(res.message, {
                          offset: '50px'
                          ,icon: 2
                          ,time: 2000
                      });
                  }
              }, "json");
            }else if(curCompany.code == 'easypaya'){
              $.post("{{url('/api/user/easypaya_get_quota')}}",
              {
                mch_id:$('#get_quato .registrationId').val(),
                  token:token,
              },function(res){
                  $('.getQuatoSubmit').prop('disabled', false);
                  if(res.status == 1){
                    // layer.msg(res.message);
                      // 打开额度配置弹框
                      let list = res.data || [];
                      quotaConfig(list)
                  }else{
                      layer.msg(res.message, {
                          offset: '50px'
                          ,icon: 2
                          ,time: 2000
                      });
                  }
              }, "json");
            }
            
        });

        function quotaConfig(list){
          let hasBankList = [];
          let nodataMchid = '';
          list.forEach(ele=>{
            if(!ele.bank_name){
              nodataMchid += `${ele.mch_id},`
            }else{
              if(curCompany.code == 'easypaya'){
                let currentDate = new Date();
                let curYear = currentDate.getFullYear();
                let curMonth = currentDate.getMonth() + 1;
                let nextMonth = curMonth + 1;
                if(curMonth<10){
                  curMonth = `0${curMonth}`
                }
                if(nextMonth<10){
                  nextMonth = `0${nextMonth}`
                }
                let startDate = ele.start_date;
                let endDate = ele.end_date;
                if(ele.bankname == '易生浙商银行'){ //易生浙商银行
                  startDate = `${curYear}${curMonth}06`;
                  endDate = `${curYear}${nextMonth}05`;
                }else if(ele.bankname == '易生杭州银行'){
                  startDate = `${curYear}${curMonth}04`;
                  endDate = `${curYear}${nextMonth}03`;
                }
                hasBankList.push({...ele,start_date:startDate,end_date:endDate})
              }else{
                hasBankList.push(ele)
              }
            }
          })
          // 获取当前商户号的银行
          layer.open({
            type: 1,
            title: false,
            closeBtn: 1,
            title: '额度配置',
            area:  ['1150px', '600px'],
            offset: 'auto', // 居中显示
            skin: 'layui-layer-nobg', //没有背景色
            shadeClose: true,
            content: $('#quato_config'),
            cancel: function(layero,index){
              layer.closeAll();
            },
            success:function(layero,index){
              table.render({
                elem: '#quatoConfigTable'
                ,height:480
                ,data:hasBankList
                ,cols: [[
                    {field: 'mch_id', title: '商户号',width:170}
                    ,{field: 'quota',  title: '额度',width:100,templet:function(d){
                      return d.quota.toFixed(2)
                    }}
                    // ,{field: 'selBank',  title: '选择银行',width:150,toolbar: '#selBankConfig'}
                    ,{field: 'bank_name',  title: '银行',width:150}
                    ,{field: 'start_date',  title: '开始日期(可编辑)',width:160,edit:'text'}
                    ,{field: 'end_date',  title: '结束日期(可编辑)',width:160,edit:'text'}
                    // ,{field: 'rate',  title: '费率(可编辑)',width:150,edit:'text',templet:function(d){
                    //   return d.rate ? `${d.rate}%` :''
                    // }}
                    ,{field: 'quota_rate',  title: '费率',width:150,edit:'text',templet:function(d){
                      return d.quota_rate ? `${d.quota_rate}%` :''
                    }}
                    ,{field: 'handleQuota',  title: '换算额度',width:120,templet: function(d){
                      return d.quota_rate ?  Math.trunc(d.quota / (d.quota_rate / 100)) : 0;
                    }}
                    ,{width:120,align:'center', fixed: 'right', toolbar: '#configtable-content-list',title: '操作'}
                ]]
                ,editMode: "single"//可编辑模式，支持：single单行、row整行、cell单元格
                ,done: function(res, curr, count){
                    $('th').css({'font-weight': 'bold', 'font-size': '15','color': 'black','background':'linear-gradient(#f2f2f2,#cfcfcf)'});	//进行表头样式设置
                    res.data.forEach(function(row, index) {
                      console.log(row,'row')
                      var selectValue = row.selBank; // 获取需要回显的值
                      if(selectValue){
                        // 使用lay-filter找到对应的select元素，并更新它的值
                        $('select[lay-filter="selBank"]').eq(index).val(selectValue);
                      }
                    });
                    // 重新渲染select元素
                    form.render('select');
                }
              });
                    }
          });
          if(nodataMchid){
            layer.open({
                title:'提示',
                content: `${nodataMchid}未配置银行和费率`,
                yes: function(index, layero){
                    //do something
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                }
            }); 
          }
        }

      // 民生联合收单-获取额度
      $('.getCmbcunionQuatoSubmit').click(function(){
          $('.getCmbcunionQuatoSubmit').prop('disabled', true);
          $.post("{{url('/api/cmbcunion/get_quota')}}",
          {
            mch_id:$('#get_cmbc_union_quato .registrationId').val(),
            act_code:$('#get_cmbc_union_quato .act_code').val(),
              token:token,
          },function(res){
              $('.getCmbcunionQuatoSubmit').prop('disabled', false);
              if(res.status == 1){
                // layer.msg(res.message, {
                //     offset: '50px'
                //     ,icon: 1
                //     ,time: 2000
                // },function(){
                  // window.location.reload();
                  // layer.closeAll();
                  // 打开额度配置弹框
                  let list = res.data || [];
                  layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 1,
                    title: '额度配置',
                    area:  ['1000px', '600px'],
                    offset: 'auto', // 居中显示
                    skin: 'layui-layer-nobg', //没有背景色
                    shadeClose: true,
                    content: $('#quato_config'),
                    cancel: function(layero,index){
                      layer.closeAll();
                    },
                    success:function(){
                      table.render({
                        elem: '#quatoConfigTable'
                        ,height:480
                        ,data:list
                        ,cols: [[
                            {field: 'mch_id', title: '商户号',width:170}
                            ,{field: 'quota',  title: '额度',width:100,templet:function(d){
                              return d.quota.toFixed(2)
                            }}
                            ,{field: 'start_date',  title: '开始日期(可编辑)',width:160,edit:'text'}
                            ,{field: 'end_date',  title: '结束日期(可编辑)',width:160,edit:'text'}
                            ,{field: 'rate',  title: '费率(可编辑)',width:150,edit:'text',templet:function(d){
                                return d.rate ? `${d.rate}%` :''
                              }}
                            ,{field: 'handleQuota',  title: '换算额度',width:120,templet: function(d){
                              return d.rate ?  Math.trunc(d.quota / (d.rate / 100)) : 0;
                            }}
                            ,{width:120,align:'center', fixed: 'right', toolbar: '#configtable-content-list',title: '操作'}
                        ]]
                        ,editMode: "single"//可编辑模式，支持：single单行、row整行、cell单元格
                        ,done: function(res, curr, count){
                            $('th').css({'font-weight': 'bold', 'font-size': '15','color': 'black','background':'linear-gradient(#f2f2f2,#cfcfcf)'});	//进行表头样式设置
                        }
                      });
                            }
                  });
                // });
              }else{
                  layer.msg(res.message, {
                      offset: '50px'
                      ,icon: 2
                      ,time: 2000
                  });
              }
          }, "json");
      });

      // 额度配置表格可编辑
      table.on('edit(quatoConfigTable)', function (obj) {
        var data = obj.data //得到所在行所有数据
        var value = obj.value; // 得到修改后的值
        var field = obj.field; // 得到字段
        console.log(field,'field')
        if(field === 'rate'){
          // 验证输入是否为数字且最多5位小数
          var regex = /^\d+(\.\d{1,5})?$/;
          if(!regex.test(value)) {
            layer.msg('请输入有效的数字，最多5位小数');
            return false;
          }
          var percent = parseFloat(value);
          if(percent < 0 || percent > 1) {
            layer.msg('百分比必须在0-1之间');
            return false;
          }
          if(value){
            // 当百分比修改时，更新
            table.reload('quatoConfigTable', {
              data: table.cache.quatoConfigTable
            });
          }
        }else if(field === 'start_date'){
          if(!value){
            layer.msg('请输入正确的开始日期');
            return false;
          }
          // if(value && !value.endsWith("01")){
          //   layer.msg('开始日期必须为当月的1号');
          //   return false;
          // }
        }else  if(field === 'end_date'){
          if(!value){
            layer.msg('请输入正确的结束日期');
            return false;
          }
        }
      })

      table.on('tool(quatoConfigTable)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var e = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的DOM对象
        if(layEvent === 'shangchuan'){
          if(e.quota_rate && e.start_date && e.end_date && e.bank_name){
            if(Number(e.start_date) > Number(e.end_date)){
              layer.msg('开始日期不能大于结束日期');
              return false;
            }
            // if(e.start_date && !e.start_date.endsWith("01")){
            //   layer.msg('开始日期必须为当月的1号');
            //   return false;
            // }
            let hsRate = Math.trunc(e.quota / (e.quota_rate / 100))
            let title = ''
            if(curCompany.code == 'easypaya' || curCompany.code == 'gtxy'){
              // title = "<div><p>确定上传以下数据吗?</p><br><p>商户号："+ e.mch_id + "</p><br><p>已选银行：" + (e.selBank && e.selBank == 1? '易生浙商银行':(e.selBank==2 ? '易生杭州银行':'')) + "</p><br><p>开始日期："+ e.start_date + "</p><br><p>结束日期："+ e.end_date + "</p><br><p>费率："+ e.rate + "%</p><br><p>换算额度："+ hsRate + "</p></div>"
              title = "<div><p>确定上传以下数据吗?</p><br><p>商户号："+ e.mch_id + "</p><br><p>银行：" + e.bank_name + "</p><br><p>开始日期："+ e.start_date + "</p><br><p>结束日期："+ e.end_date + "</p><br><p>费率："+ e.quota_rate + "%</p><br><p>换算额度："+ hsRate + "</p></div>"
            }else{
              title = "<div><p>确定上传以下数据吗?</p><br><p>商户号："+ e.mch_id + "</p><br><p>开始日期："+ e.start_date + "</p><br><p>结束日期："+ e.end_date + "</p><br><p>费率："+ e.rate + "%</p><br><p>换算额度："+ hsRate + "</p></div>"
            }
            layer.confirm(title, function () {
              var scLoading = layer.msg('上传中..', {
                  icon: 16
                  ,shade: 0.3
                  ,time: false
              });
              let starts = e.start_date ? e.start_date.replace(/-/g, "") :'';
              let ends = e.end_date ? e.end_date.replace(/-/g, "") :'';
              $.post("{{url('/api/user/company_merchant_quota_add')}}",
              {
                mch_id:e.mch_id,
                token:token,
                company_rule_id:curCompany.id,
                company_code:curCompany.code,
                start_date:starts,
                end_date:ends,
                quota:hsRate
              },function(result){
                if (result.status == 1) {
                  layer.msg(result.message, {
                      icon: 1,
                      time: 1000 //1秒关闭（如果不配置，默认是3秒）
                  }, function () {
                      layer.close(scLoading)
                  });
                  tr.find("a[lay-event='shangchuan']").prop('disabled', true);
                  tr.find("a[lay-event='shangchuan']").text('已上传');
                }
                else {
                    layer.msg(result.message);
                }
              }, "json")
            });
            
          }else {
            layer.msg('请输入正确的数据且检查无误后再上传!');
          }
        }
      })
      

      //下拉框回显
      form.on('select(selBank)', function (data) {
        console.log(data,'data-----')
        let ee = data.elem.value; //当前字段变化的值
        var tr = $(data.elem).closest('tr'); // 获取当前行元素
        var rowIndex = tr.data('index'); // 获取行索引
        var tableId = 'quatoConfigTable'; // 表格 ID
        // 获取当前行数据
        var rowData = {...table.cache[tableId][rowIndex]};
        let currentDate = new Date();
        let curYear = currentDate.getFullYear();
        let curMonth = currentDate.getMonth() + 1;
        let nextMonth = curMonth + 1;
        if(curMonth<10){
          curMonth = `0${curMonth}`
        }
        if(nextMonth<10){
          nextMonth = `0${nextMonth}`
        }
        if(ee == 1){ //易生浙商银行
          let startDate = `${curYear}${curMonth}06`;
          let endDate = `${curYear}${nextMonth}05`;
          // 修改当前行数据（关键步骤）
          rowData['selBank'] = data.value; // 更新选择银行
          rowData['start_date'] = startDate;
          rowData['end_date'] = endDate;
          rowData['rate'] = 0.25;
          rowData['handleQuota'] = rowData.rate ?  Math.trunc(rowData.quota / (rowData.rate / 100)) : 0;
          // 更新表格缓存（确保数据持久化）
          table.cache[tableId][rowIndex] = rowData;
          table.reload('quatoConfigTable', {
            data: table.cache.quatoConfigTable,
          });

        }else if(ee == 2){  //易生杭州银行
          let startDate = `${curYear}${curMonth}04`;
          let endDate = `${curYear}${nextMonth}03`;
          // 修改当前行数据（关键步骤）
          rowData['selBank'] = data.value; // 更新选择银行
          rowData['start_date'] = startDate;
          rowData['end_date'] = endDate;
          rowData['rate'] = 0.25;
          rowData['handleQuota'] = rowData.rate ?  Math.trunc(rowData.quota / (rowData.rate / 100)) : 0;
          // 更新表格缓存（确保数据持久化）
          table.cache[tableId][rowIndex] = rowData; 
          table.reload('quatoConfigTable', {
            data: table.cache.quatoConfigTable,
          });
        }else {
          layer.msg('请选择银行');
          rowData['selBank'] = data.value; // 更新选择银行
          return false;
        }
      })

      $('.exportData').click(function (){
        // 默认情况下，对象属性（如"姓名"）会成为工作表的第一行（表头）
        // 2. 定义英文字段到中文表头的映射
        let datalist = companyMerList.map(ele=>{
            return {
                mch_id:ele.mch_id,
                store_id:ele.store_id,
                quota:ele.quota,
                no_use_quota:ele.no_use_quota,
                store_name:ele.store_name
            }
        })
        const headerMap = {
            'mch_id': '商户号',
            'store_id': '门店ID',
            'quota': '额度',
            'no_use_quota':'未使用额度',
            'store_name':'门店名称'
        };
        const dataWithChineseHeader = datalist.map(row => {
            const newRow = {};
            for (const key in row) {
                // 使用映射表获取中文表头，如果找不到则保留原键名
                const chineseHeader = headerMap[key] || key;
                newRow[chineseHeader] = row[key];
            }
            return newRow;
        });
        const worksheet = XLSX.utils.json_to_sheet(dataWithChineseHeader);

        // 3. 创建一个新的工作簿并将工作表添加进去
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "商户号"); // "员工信息"是工作表名称

        // 4. 将工作簿写入文件并触发下载
        // 'xlsx' 是文件格式， type: 'array' 是推荐的写入方式
        const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
        const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });

        // 5. 创建下载链接并触发点击
        const url = window.URL.createObjectURL(blob);
        const downloadLink = document.createElement("a");
        downloadLink.href = url;
        downloadLink.download = `${curCompany.name}_商户号列表.xlsx`; // 设置文件名
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
        window.URL.revokeObjectURL(url); // 释放内存
      })

    });

  </script>

</body>
</html>
